<template>
	<view class="">
		<!-- 顶部个人信息 -->
		<view class="bg-white">
			<view class="flex padding" @click="handleClick">
				<view class="padding-lr-xs">
					<!-- <view class="cu-avatar lg round" :style="{ backgroundImage: `url(${user.userPhotoUri || 'static/avatar.jpg'})` }"> -->
					<view class="cu-avatar lg round" :style="{ backgroundImage: `url('static/avatar.jpg')` }">
						<!-- ${user.avatar || 'static/avatar.jpg'} -->
						<!-- 这里的 :mask-click 直白说就是设置点击谈窗外的空白处是否关闭弹窗的，如果改为true则实现点击空白关闭弹窗的效果 -->
						<uni-drawer ref="showRight" mode="right" :mask-click="true" style="width: 100%;">
							<scroll-view style="height: 100%; width: 100%;" scroll-y="true">
								<iui-button class="edit-button-edit" type="primary" style="display: block"
									@click="showPopup">个人编辑</iui-button>
								<iui-button class="edit-button" type="primary" @click="outlogin"
									style="display: block">退出登录</iui-button>
								<transition name="fade">
									<div class="popup" v-if="showPopupContent">
										<div class="popup-content" style="height: 80%;">

											<view class="input-article-photo"
												style="border: 1px solid #ccc; border-radius: 8px; padding: 10px; background-color: #f9f9f9; ">
												<uni-file-picker limit="1" title="上传新图片作为头像" @select="selectPhoto"
													style="border: 1px dashed #aaa; border-radius: 8px; padding: 10px; background-color: #fff;">
												</uni-file-picker>
											</view>

											<view class="ipt">
												<uni-icons type="contact" size="24" color="rgb(66,157,250)"></uni-icons>
												<input type="text" value="" v-model="newUser.username"
													placeholder="请输入新用户名" />
											</view>

											<!-- <view class="ipt">
												<uni-icons type="eye" size="24" color="rgb(66,157,250)"></uni-icons>
												<input type="password" value="" v-model="newUser.password"
													placeholder="请输入新密码" />
											</view> -->

											<!-- <view class="ipt">
												<uni-icons type="eye" size="24" color="rgb(66,157,250)"></uni-icons>
												<input type="number" id="phoneNumber" pattern="\d{11}" maxlength="11"
													inputmode="numeric" v-model="newUser.phoneNum" placeholder="请输入新手机号"
													required>
											</view> -->

											<view class="ipt">
												<uni-icons type="eye" size="24" color="rgb(66,157,250)"></uni-icons>
												<input type="text" value="" v-model="newUser.userEmail"
													placeholder="请输入新邮箱" />
											</view>

											<view class="ipt">
												<button class="action-button small-button" @click="updateUser"
													style="width: 100%;">保存</button>
											</view>
											<view class="ipt">
												<button class="action-button small-button" @click="hidePopup"
													style="width: 100%;">取消</button>
											</view>
										</div>
									</div>
								</transition>
							</scroll-view>
						</uni-drawer>
					</view>
				</view>
				<view class="padding-xs text-xl text-black">
					<view>{{user.username}}</view>
					<view class="cu-tag round line-red sm">lv.99 ></view>
				</view>
			</view>
		</view>
		<!-- 基本数据 -->
		<view class="cu-list grid col-4 no-border padding-lr-xs radius-lg-bottom">
			<view class="cu-item" @tap="toMyArticle">
				<view class="text-black text-bold text-xxl">
					
				</view>
				<text>我的文章</text>
			</view>
			<view class="cu-item" @click="toMyCollection">
				<view class="text-black text-bold text-xxl">
					
				</view>
				<text>收藏</text>
			</view>
			<view class="cu-item" @click="toBrowsingHistory">
				<view class="text-black text-bold text-xxl">
					
				</view>
				<text>浏览记录</text>
			</view>
			<view class="cu-item" @click="toMyFollwer">
				<view class="text-black text-bold text-xxl">
					
				</view>
				<text>我的粉丝</text>
			</view>
		</view>
		<!-- 会员 -->
		<view class="margin-top-sm padding-lr-xs">
			<view class="bg-brown light radius-lg shadow-blur">
				<view class="flex padding-tb-sm padding-lr-sm justify-between">
					<view class="padding-xs">
						<view>会员描述文本</view>
					</view>
					<view class="">
						<view class="button" style="text-align: center; width: 175rpx;">
							<text>开通会员</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 常用功能 -->
		<view class="cu-bar margin-lr-xs margin-top-sm grid col-4 no-border bg-white radius-lg-top">
			<view class="action">
				<text class="text-xl text-black">用户服务</text>
			</view>
			<view class="action">
				<text class="">更多服务<text class="cuIcon-right"></text></text>
			</view>
		</view>
		<view class="cu-list grid col-4 no-border text-black margin-lr-xs padding-bottom radius-lg-bottom"
			@tap="toWallet">
			<view class="cu-item">
				<view class="cuIcon-moneybagfill text-orange text-shadow" style="font-size: 56rpx;">
				</view>
				<text>钱包</text>
			</view>
		</view>
		<!-- <view class="cu-list grid col-4 no-border text-black margin-lr-xs padding-bottom radius-lg-bottom">
	    <view class="cu-item" v-for="item in iconList" :key="item.name" :bindtap="item.bindtap">
	      <view :class="['cuIcon-'+item.icon,'text-'+item.color,'text-shadow']" style="font-size: 56rpx;">
	        <view class="cu-tag badge" v-if="item.badge!=0">
	          <block v-if="item.badge!=1">{{item.badge>99?"99+":item.badge}}</block>
	        </view>
	      </view>
	      <text>{{item.name}}</text>
	    </view>
	  </view> -->
		<!-- 广告（可选） -->
		<view class="margin-top-sm padding-lr-xs">
			<view class="bg-white light radius-lg shadow-blur">
				<view class="flex padding-tb-sm padding-lr-sm justify-between">
					<view class="padding-xs">
						<view class="text-xl text-black">广告或其他增值内容标题</view>
						<view class="padding-top-xs">文本<text class="text-red text-bold"> 文本 </text><text
								class="cuIcon-roundrightfill text-red"></text></view>
					</view>
					<view class="">
						<view class="cu-btn round bg-gradual-pinknew margin-top-sm">文本</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 其他功能 -->
		<view class="cu-bar margin-lr-xs margin-top grid col-4 no-border bg-white radius-lg-top">
			<view class="action">
				<text class="text-xl">其他功能</text>
			</view>
		</view>
		<view class="cu-list grid col-4 no-border text-black margin-lr-sm padding-bottom radius-lg-bottom">
			<view class="cu-item" v-for="(item,index) in iconOtherList" :key="item.name" :bindtap="item.bindtap">
				<view :class="['cuIcon-'+item.icon,'text-'+item.color,'text-shadow']" style="font-size: 56rpx;">
					<view class="cu-tag badge" v-if="item.badge!=0">
						<block v-if="item.badge!=1">{{item.badge>99?"99+":item.badge}}</block>
					</view>
				</view>
				<text>{{item.name}}</text>
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue';

	import {
		loadInfo
	} from '/pages/mine/api/mine.js';
	
	import {
		update
	} from '/pages/mine/api/mine.js';

	import {
		outLogin
	} from '/pages/mine/api/mine.js';

	import {
		faBlog
	} from '@fortawesome/free-solid-svg-icons';
	
	import { onLoad, onShow } from "@dcloudio/uni-app";

	const user = ref({
		id: "",
		userPhotoUri: "",
		username: "",
		userPhoneNum: "",
	})

	const newUser = ref({
		id: "",
		userName: "",
		userPhoto: "",
		userEmail: "",
		
	})

	let userId = ref(null);
	// const user = ref(uni.getStorageSync("user"))
	
	const photoUri = ref(null);


	const iconList = ref([{
		icon: 'moneybagfill',
		color: 'blue',
		badge: 0,
		name: '钱包',
		bindtap: "toWallet"
	}, {
		icon: 'presentfill',
		color: 'red',
		badge: 0,
		name: '服务2',
		bindtap: "bindZan"
	}, {
		icon: 'formfill',
		color: 'purple',
		badge: 0,
		name: '服务3',
		bindtap: "showResource"
	}, {
		icon: 'shopfill',
		color: 'green',
		badge: 0,
		name: '服务4',
		bindtap: "bindPoint"
	}])

	const iconOtherList = ref([{
		icon: 'location',
		color: 'blue',
		badge: 0,
		name: '功能1'
	}, {
		icon: 'service',
		color: 'blue',
		badge: 0,
		name: '功能2',
		bindtap: "bindZan"
	}, {
		icon: 'mark',
		color: 'blue',
		badge: 0,
		name: '功能',
		bindtap: "showResource"
	}, {
		icon: 'mail',
		color: 'blue',
		badge: 0,
		name: '功能4',
		bindtap: "bindCollect"
	}, {
		icon: 'settings',
		color: 'blue',
		badge: 0,
		name: '功能5',
		bindtap: "bindZan"
	}])

	const toMyArticle = () => {
		uni.navigateTo({
			url: './myArticle'
		})
	};

	const toMyCollection = () => {
		uni.navigateTo({
			url: './myCollection'
		})
	};

	const toBrowsingHistory = () => {
		uni.navigateTo({
			url: './browsingHistory'
		})
	};

	const toMyFollwer = () => {
		uni.navigateTo({
			url: './myFollower'
		})
	};


	const toWallet = () => {
		uni.navigateTo({
			url: './wallet'
		})
	};
	
	onShow(() =>{
		checkLoginStatus();
	})

	//是否登录
	const isLoggedIn = ref(false);

	const showRight = ref(null); // 创建一个 ref 来引用 Sidebar 组件

	const checkLoginStatus = () => {
		if (uni.getStorage("VisitToken") != null && uni.getStorage("RefreshToken") != null) {
			//表示已经登录
			const userDataString = localStorage.getItem("UserId");
			const userData = JSON.parse(userDataString);
			const visitUserId = ref(null);
			visitUserId.value = userData.data;
			userId = visitUserId;
			isLoggedIn.value = true;
			loadUserInfo(userId);
		} else {
			isLoggedIn.value = false;
		}
	}

	const loadUserInfo = async (userId) => {
		let res = await loadInfo(userId);
		console.log(res);
		user.value.id = res.data.id;
		user.value.userPhotoUri = res.data.userPhoto;
		user.value.userPhoneNum = res.data.phoneNum;
		user.value.username = res.data.username;
		newUser.value.id = res.data.id;
		newUser.value.username = res.data.username;
		newUser.value.userEmail = res.data.userEmail;
		console.log(user);
	}

	const handleClick = () => {
		if (isLoggedIn.value) {
			showRight.value.open(); // 使用 ref 访问 Sidebar 组件的方法
		} else {
			navigateToLogin();
		}
	};

	const navigateToLogin = () => {
		uni.navigateTo({
			url: '/pages/login/index'
		});
	};

	// 侧边弹窗---------------------------------------------------------------
	const showPopupContent = ref(false);

	const handleClose = () => {
		if (confirm('是否关闭本弹窗？')) {
			showPopupContent.value = false;

		}
	}

	const showPopup = () => {
		showPopupContent.value = true;
	};

	const hidePopup = () => {

		showPopupContent.value = false;
	};

	// 编辑个人资料-----------------------------------------
	//定义选择封面图片方法
	const selectPhoto = async (selectFiles) => {
		console.log(selectFiles.tempFiles[0].path);
		if (selectFiles.tempFiles[0] != null) {
			const file = selectFiles.tempFiles[0];
			photoUri = file.path;
			// console.log(response);
		} else {
			console.log('No file selected');
		}
	}

	const updateUser = async () => {
		// 获取 Blob URL
		const blobUrl = photoUri;
		
		// 使用 fetch API 获取 Blob 内容
		const response = await fetch(blobUrl);
		const blob = await response.blob();
		
		// 创建一个文件对象
		const file = new File([blob], 'newFileName.jpg', {
			type: 'image/jpeg'
		});
		
		// 使用 uni.uploadFile 上传文件
		const uploadResult = await new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:9091/file/upload', // 替换为你的后端接口地址
				filePath: URL.createObjectURL(file), // 使用 createObjectURL 生成文件路径
				name: 'file', // 对应后端接收的参数名
				formData: {
					// 可以添加其他表单数据
					// key: 'value'
				},
				success: (res) => {
					console.log('Upload success:', res.data);
					resolve(res);
					// res.data是一个Json字符串，需要给它转换为对象
					const userPhotoData = JSON.parse(res.data);
					newUser.value.userPhoto = userPhotoData.data;
					console.log(newUser);
				},
				fail: (err) => {
					console.error('Upload error:', err);
					reject(err);
				}
			});
		});
		const newUserJson = JSON.stringify(newUser.value);
		//上面获取用户更新的用户的信息
		console.log(newUserJson);
		let res = await update(newUserJson);
	}
	
	// 退出登录
	const outlogin = async() => {
		//向后端发送一个get请求，删除redis中存储的session数据
		//清空localStorage中的所有token，并返回到home页
		let res = await outLogin(userId);
		localStorage.removeItem('VisitToken');
		localStorage.removeItem('RefreshToken');
		localStorage.removeItem('UserId');
		location.reload();
	}
	
	
</script>

<style>
	.button {
		width: 5em;
		height: 2.3em;
		display: flex;
		padding: 0.8em 1.1em;
		gap: 0.4rem;
		border: none;
		font-weight: bold;
		font-size: 100%;
		border-radius: 30px;
		cursor: pointer;
		text-shadow: 2px 2px 3px rgb(136 0 136 / 50%);
		line-height: 70%;
		background: linear-gradient(15deg,
				#880088,
				#aa2068,
				#cc3f47,
				#de6f3d,
				#f09f33,
				#de6f3d,
				#cc3f47,
				#aa2068,
				#880088) no-repeat;
		background-size: 300%;
		background-position: left center;
		transition: background 0.3s ease;
		color: #fff;
	}

	.button:hover {
		background-size: 320%;
		background-position: right center;
	}

	.button:hover svg {
		fill: #fff;
	}

	.button svg {
		width: 23px;
		fill: #f09f33;
		transition: 0.3s ease;
	}

	/* ------------------------------------------------------------ */
	.edit-button {
		background-color: #FFA07A;
		/* 淡橙色 */
		border: 1px solid #FFA07A;
		color: #fff;
		padding: 10px 150rpx;
		text-align: center;
		text-decoration: none;
		display: inline-block;
		font-size: 16px;
		margin: 4px 2px;
		cursor: pointer;
		border-radius: 5px;
		transition: background-color 0.3s ease;
	}

	.edit-button:hover {
		background-color: #FF8C00;
		/* 更深的橙色 */
	}

	.edit-button-edit {
		background-color: #FFA07A;
		/* 淡橙色 */
		border: 1px solid #FFA07A;
		color: #fff;
		padding: 10px 150rpx;
		text-align: center;
		text-decoration: none;
		display: inline-block;
		font-size: 16px;
		margin: 4px 2px;
		cursor: pointer;
		border-radius: 5px;
		transition: background-color 0.3s ease;
	}

	.edit-button-edit:hover {
		background-color: #FF8C00;
		/* 更深的橙色 */
	}

	/* ------------------------------------------------------------ */

	.popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.popup-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		position: relative;
	}

	.input-item {
		margin-bottom: 15px;
		border: 1px solid #ccc;
		border-radius: 5px;
		padding: 10px;
		box-sizing: border-box;
	}

	.input-field {
		width: 100%;
		padding: 10px;
		box-sizing: border-box;
		border: 1px solid #ccc;
		border-radius: 5px;
		font-size: 16px;
	}

	.actions {
		position: absolute;
		bottom: 20px;
		right: 20px;
		display: flex;
		gap: 10px;
	}

	.action-button {
		background-color: #ffa07a;
		border: none;
		color: white;
		padding: 10px 15px;
		text-align: center;
		text-decoration: none;
		display: inline-block;
		font-size: 14px;
		cursor: pointer;
		border-radius: 5px;
		transition: background-color 0.3s ease;
	}

	.small-button {
		font-size: 14px;
		padding: 8px 12px;
	}

	.action-button:hover {
		background-color: #45a049;
	}

	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.3s;
	}

	.fade-enter-from,
	.fade-leave-to {
		opacity: 0;
	}

	/* -----------------------------------------------------------------------------------------------  */

	.ipt {
		height: 86rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-bottom: 40rpx;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		padding-left: 10rpx;
	}
</style>